﻿namespace DCHealthCheck.MvcWeb.Classes.DataServices {

    #region Usings
    using DCHealthCheck.Common;
    using DCHealthCheck.DomainModel;
    using DCHealthCheck.MvcWeb.Classes.ViewModels;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Text;
    using System.Threading;
    using System.Web;
    using System.Web.Mvc;
    #endregion

    public class NetstatInfoDataService : BaseDataService, INetstatInfoDataService {

        #region Members
        private readonly IRepository<NetstatInfo, IEntityManager> NetstatInfoRepository;

        private readonly Expression<Func<NetstatInfo, object>>[] NetstatInfoIncludedEntities;
        #endregion

        #region Constructor
        public NetstatInfoDataService(
            IRepository<DomainController, IEntityManager> dcRepository,
            IRepository<NetstatInfo, IEntityManager> netstatInfoRepository) : base(dcRepository) {
            if (netstatInfoRepository == null) {
                throw new ArgumentNullException("netstatInfoRepository");
            }
            this.NetstatInfoRepository = netstatInfoRepository;
            this.NetstatInfoIncludedEntities = new Expression<Func<NetstatInfo, object>>[] {
                (x) => x.SystemInfo,
                (x) => x.SystemInfo.DomainController,
                (x) => x.SystemInfo.ProcessInfos
            };

        } 
        #endregion

        #region Methods
        private void BuildFilterSelectLists(NetstatInfoViewModel viewModel) {

            // build common selectlists
            var filteredDCIds = this.GetFilteredNetstatInfos(viewModel)
                .Select(x => x.SystemInfo.DomainController.Id)
                .Distinct()
                .ToList();
            base.BuildFilterSelectLists(filteredDCIds, viewModel);

            var selectListItem = new SelectListItem();
            selectListItem.Text = "(Any)";
            selectListItem.Value = string.Empty;

            // build view model specific select lists
            viewModel.ProcessExecutableSelectListItems.Add(selectListItem);

            var processExecutablePaths = new List<string>();
            var processExecutableNames = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            var netstatInfos = this.GetFilteredNetstatInfos(viewModel);
            var executableInfos = netstatInfos
                .Select(x =>
                    new { x.ProcessInfo.Executable, x.ProcessInfo.ExecutablePath })
                .ToList();

            foreach (var executableInfo in executableInfos) {
                if (string.IsNullOrWhiteSpace(executableInfo.ExecutablePath)) continue;

                // ignore the Trend OfficeScan RealTime Monitor Watchdog processes, that have a random file name 
                // and reside in C:\Windows\Temp
                if (executableInfo.ExecutablePath.StartsWith(@"C:\Windows\Temp\", StringComparison.CurrentCultureIgnoreCase)) {
                    if ((executableInfo.Executable.Length >= 4) && (executableInfo.Executable.Length <= 7)) continue;
                }

                if (!string.IsNullOrWhiteSpace(executableInfo.Executable)) {
                    if (!processExecutableNames.ContainsKey(executableInfo.Executable)) {
                        processExecutableNames.Add(executableInfo.Executable, executableInfo.ExecutablePath);
                    }
                }
            }

            foreach (var processExecutable in processExecutableNames.Keys) {
                selectListItem = new SelectListItem();
                selectListItem.Text = processExecutable;
                if (!string.IsNullOrWhiteSpace(viewModel.ProcessExecutable) && string.Equals(viewModel.ProcessExecutable, processExecutable, StringComparison.OrdinalIgnoreCase)) {
                    selectListItem.Selected = true;
                }
                selectListItem.Value = processExecutableNames[processExecutable];
                viewModel.ProcessExecutableSelectListItems.Add(selectListItem);
            }
        }

        public string GetCSVData(NetstatInfoViewModel viewModel) {

            if (viewModel == null) {
                throw new ArgumentNullException("viewModel");
            }

            viewModel.Initialize();
            viewModel.SkipCount = 0;
            viewModel.TakeCount = int.MaxValue;
            this.ProcessData(viewModel, false, false);

            var fileData = new StringBuilder();

            fileData.AppendLine(NetstatInfo.CSVHeader);
            foreach (var record in viewModel.NetstatInfos) {
                fileData.AppendLine(record.ToCSVString());
            }

            return fileData.ToString();
        }

        private IQueryable<NetstatInfo> GetFilteredNetstatInfos(NetstatInfoViewModel viewModel) {

            var netstatInfos = this.NetstatInfoRepository.Get(this.NetstatInfoIncludedEntities);

            if (viewModel.SystemInfoId != Guid.Empty) {
                netstatInfos = netstatInfos.Where(x => x.SystemInfo.Id == viewModel.SystemInfoId);
            }
            else {
                if (viewModel.DomainControllerId != Guid.Empty) {
                    netstatInfos = netstatInfos.Where(x => x.SystemInfo.DomainController.Id == viewModel.DomainControllerId);
                }

                if (viewModel.Date != DateTime.MinValue) {
                    netstatInfos = netstatInfos.Where(x => x.SystemInfo.CheckDateTimeUTC == viewModel.Date);
                }
                else {
                    if (viewModel.StartDate.HasValue) {
                        netstatInfos = netstatInfos.Where(x => x.SystemInfo.CheckDateUTC >= viewModel.StartDate);
                    }
                    if (viewModel.EndDate.HasValue) {
                        netstatInfos = netstatInfos.Where(x => x.SystemInfo.CheckDateUTC <= viewModel.EndDate);
                    }
                }

                if (!string.IsNullOrWhiteSpace(viewModel.ADSite)) {
                    netstatInfos = netstatInfos
                        .Where(x => x.SystemInfo.DomainController.ADSite == viewModel.ADSite);
                }
                if (!string.IsNullOrWhiteSpace(viewModel.Domain)) {
                    netstatInfos = netstatInfos
                        .Where(x => x.SystemInfo.DomainController.NetbiosDomain == viewModel.Domain);
                }
                if (!string.IsNullOrWhiteSpace(viewModel.OSVersion)) {
                    netstatInfos = netstatInfos
                        .Where(x => x.SystemInfo.DomainController.OSVersion == viewModel.OSVersion);
                }
                if (!string.IsNullOrWhiteSpace(viewModel.DCName)) {
                    netstatInfos = netstatInfos
                        .Where(x => x.SystemInfo.DomainController.SamAccountName == viewModel.DCName);
                }

                if (!string.IsNullOrWhiteSpace(viewModel.ProcessExecutable)) {
                    netstatInfos = netstatInfos.Where(x => x.ProcessInfo.ExecutablePath.ToUpper().Contains(viewModel.ProcessExecutable.ToUpper()));
                }
            } // else if (this.SystemInfoId != Guid.Empty)

            return netstatInfos;
        }

        public void ProcessData(NetstatInfoViewModel viewModel, bool initialize = true, bool buildFilterSelectLists = true) {
            Global.DefaultLog.DebugFormat("[ThreadId: {0}] {1}", Thread.CurrentThread.ManagedThreadId, Extensions.CurrentMethodName());

            try {
                if (initialize) {
                    viewModel.Initialize();
                }

                var netstatInfos = this.GetFilteredNetstatInfos(viewModel);
                viewModel.DisplayTotalResults = netstatInfos.Count();

                #region Skip count, take, and sorting
                if (!string.IsNullOrWhiteSpace(viewModel.SortColumn)) {
                    if (viewModel.CurrentSortDirection == System.Web.Helpers.SortDirection.Ascending) {
                        viewModel.NetstatInfos = netstatInfos
                            .OrderBy(viewModel.SortColumn)
                            .Skip(viewModel.SkipCount.Value)
                            .Take(viewModel.TakeCount.Value)
                            .ToList();
                    }
                    else {
                        viewModel.NetstatInfos = netstatInfos
                            .OrderByDescending(viewModel.SortColumn)
                            .Skip(viewModel.SkipCount.Value)
                            .Take(viewModel.TakeCount.Value)
                            .ToList();
                    }
                }
                else {
                    viewModel.NetstatInfos = netstatInfos
                        .OrderBy(x => x.ProcessId)
                        .Skip(viewModel.SkipCount.Value)
                        .Take(viewModel.TakeCount.Value)
                        .ToList();
                }
                #endregion

                viewModel.GetPageCounts();
                if (buildFilterSelectLists) {
                    this.BuildFilterSelectLists(viewModel);
                }
            }
            catch (Exception e) {
                Global.DefaultLog.DebugFormat("[ThreadId: {0}] {1} {2}", Thread.CurrentThread.ManagedThreadId, Extensions.CurrentMethodName(), e.VerboseExceptionString());
            }
        }
        #endregion
    }
}